﻿@using System.Web.Script.Serialization
@model BusinessLogic.DTO.PositionDTO

@{
    ViewBag.Title = "AddPosition";
    Layout = "~/Views/Shared/_adminLayout.cshtml";
}
<script type="text/javascript"> 
    var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));
    
    function DifficultiesData(data) {
        this.DifficultyID = ko.observable(data.DifficultyID);
        this.DifficultyName = ko.observable(data.DifficultyName);
        this.selected = ko.observable(false);
        this.Quantity = ko.observable(0);
    }
    
    function QuestionTypeData(data) {
        this.QuestionTypeID = ko.observable(data.QuestionTypeID);
        this.Type = ko.observable(data.Type);
        this.selected = ko.observable(false);
        this.Quantity = ko.observable(0);
    }
    
    function CategoryData(data) {
        this.CategoryID = ko.observable(data.CategoryID);
        this.Name = ko.observable(data.Name);
        this.selected = ko.observable(false);
    }
    
    function CategoryToPositionData(data) {
        this.CategoryID = ko.observable(data.CategoryID);
        this.CategoryToPositionID = ko.observable(data.CategoryToPositionID);
        this.PositionID = ko.observable(data.PositionID);
    }
    
    function QuestionDifficultiesToPositionData(data) {
        this.QuestionDifficultyToPositionID = ko.observable(data.QuestionDifficultyToPositionID);
        this.DifficultyID = ko.observable(data.DifficultyID);
        this.PositionID = ko.observable(data.PositionID);
        this.Quantity = ko.observable(data.Quantity);
    }
    
    function QuestionTypesToPositionData(data) {
        this.QuestionTypeToPositionID = ko.observable(data.QuestionTypeToPositionID);
        this.QuestionTypeID = ko.observable(data.QuestionTypeID);
        this.PositionID = ko.observable(data.PositionID);
        this.Quantity = ko.observable(data.Quantity);
    }

    var ViewModel = function() {
        var self = this;
        self.Difficulties = ko.observableArray([]);
        self.QuestionTypes = ko.observableArray([]);
        self.Categories = ko.observableArray([]);
        self.CategoryToPosition = ko.observableArray([]);
        self.QuestionDifficultiesToPosition = ko.observableArray([]);
        self.QuestionTypesToPosition = ko.observableArray([]);
        self.Position = ko.observable();
        self.questionAmountError = ko.observable();
        
        self.error = function() {
            var ErrorSpan = document.getElementById('errorSpan');
            
            if(ErrorSpan == null)
                return;

            if(self.questionAmountError)
                ErrorSpan.innerHTML = "<-- Niezgodna liczeba pytan ustawiona w pozimie trudności i typach";
            else {
                ErrorSpan.innerHTML = "";
            }
        };

        self.questionAmount = ko.computed(function() {
            var DifficultQuesionAmount = 0;
            var TypeQuestionAmount = 0;
            for (var i = 0; i < self.Difficulties().length; i++) {
                if(self.Difficulties()[i].selected())
                    DifficultQuesionAmount += parseInt(self.Difficulties()[i].Quantity());
            }
            for (var i = 0; i < self.QuestionTypes().length; i++) {
                if(self.QuestionTypes()[i].selected())
                    TypeQuestionAmount += parseInt(self.QuestionTypes()[i].Quantity());
            }
            if(DifficultQuesionAmount == TypeQuestionAmount)
            {
                self.questionAmountError = false;
                self.error();
                return DifficultQuesionAmount;
            }
            else if(DifficultQuesionAmount > TypeQuestionAmount) {
                self.questionAmountError = true;
                self.error();
                return DifficultQuesionAmount;
            }
            else{
                self.questionAmountError = true;
                self.error();
                return TypeQuestionAmount;
            }
        });

        self.CategoriesModify = function(category) {
            if(category.selected()) {
                self.CategoryToPosition.push({
                    CategoryID: category.CategoryID(),
                    CategoryToPositionID: "",
                    PositionID: ""
                });
            }
            else {
                for(var i = 0;i < self.CategoryToPosition().length;i++) {
                    if(self.CategoryToPosition()[i].CategoryID == category.CategoryID()) {
                        self.CategoryToPosition.remove(self.CategoryToPosition()[i]);
                        break;
                    }
                    }   
                }
            return true;
        };

        self.QuestionDifficultiesToPositionModify = function(difficulty) {
            if(difficulty.selected()) {
                self.QuestionDifficultiesToPosition.push({
                    DifficultyID: difficulty.DifficultyID(),
                    QuestionDifficultyToPositionID: "",
                    PositionID: "",
                    Quantity: difficulty.Quantity()       
                });
               }
            else {
                for(var i = 0;i < self.QuestionDifficultiesToPosition().length;i++) {
                    if(self.QuestionDifficultiesToPosition()[i].DifficultyID == difficulty.DifficultyID()) {
                        self.QuestionDifficultiesToPosition.remove(self.QuestionDifficultiesToPosition()[i]);
                        break;
                    }
                }   
            }
            return true;
        };

        self.QuestionTypesToPositionModify = function(type) {
            if(type.selected()) {
                self.QuestionTypesToPosition.push({
                    QuestionTypeID: type.QuestionTypeID(),
                    QuestionTypeToPositionID: "",
                    PositionID: "",
                    Quantity: type.Quantity()        
                });
            }
            else {
                for(var i = 0;i < self.QuestionDifficultiesToPosition().length;i++) {
                    if(self.QuestionDifficultiesToPosition()[i].DifficultyID == type.DifficultyID()) {
                        self.QuestionDifficultiesToPosition.remove(self.QuestionDifficultiesToPosition()[i]);
                        break;
                    }
                }   
            }
            return true;
        };

        self.updateQuantities = function ()
        {
            //Difficulty
            for (var i = 0; i < self.QuestionDifficultiesToPosition().length; i++) {
                for (var j = 0; j < self.Difficulties().length; j++) {
                    if(self.QuestionDifficultiesToPosition()[i].DifficultyID ==  self.Difficulties()[j].DifficultyID()) {
                        self.QuestionDifficultiesToPosition()[i].Quantity = self.Difficulties()[j].Quantity();
                        break;
                    }
                }
            }
            //Type
            for (var i = 0; i < self.QuestionTypesToPosition().length; i++) {
                for (var j = 0; j < self.QuestionTypes().length; j++) {
                    if(self.QuestionTypesToPosition()[i].QuestionTypeID ==  self.QuestionTypes()[j].QuestionTypeID()) {
                        self.QuestionTypesToPosition()[i].Quantity = self.QuestionTypes()[j].Quantity();
                        break;
                    }
                }
            }
        };

        self.loadData = function() {
            var mappedDifficulties = $.map(initialData.Difficulties, function(item) { return new DifficultiesData(item); });
            self.Difficulties(mappedDifficulties);
            
            var mappedQuestionTypes = $.map(initialData.QuestionTypes, function(item) { return new QuestionTypeData(item); });
            self.QuestionTypes(mappedQuestionTypes);
            
            var mappedCategories = $.map(initialData.Categories, function(item) { return new CategoryData(item); });
            self.Categories(mappedCategories);
            /*var mappedCategoryToPosition = $.map(initialData.CategoryToPosition, function(item) { return new CategoryToPositionData(item) });
            self.CategoryToPosition(mappedCategoryToPosition);
            var mappedQuestionDifficultiesToPosition = $.map(initialData.QuestionDifficultiesToPosition, function(item) { return new QuestionDifficultiesToPositionData(item) });
            self.QuestionDifficultiesToPosition(mappedQuestionDifficultiesToPosition);
            var mappedQuestionTypesToPositionData = $.map(initialData.QuestionTypesToPositionData, function(item) { return new QuestionTypesToPositionData(item) });
            self.QuestionTypesToPositionData(mappedQuestionTypesToPositionData);*/

            self.Position = ko.mapping.fromJS(initialData.Position);
        };

        self.save = function() {

            if(self.questionAmountError) {
                alert("Popraw błędy!");
                return;
            }

            self.updateQuantities();

            $.ajax("/Position/Save", {
                data: ko.toJSON({ 
                    Position: self.Position,
                    CategoryToPosition: self.CategoryToPosition,
                    QuestionDifficultyToPosition: self.QuestionDifficultiesToPosition,
                    QuestionTypeToPosition: self.QuestionTypesToPosition
                }),
                type: "post", contentType: "application/json",
                success: function(result) { window.location.href = result; },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }; 

    };

    var viewModel = new ViewModel();
    viewModel.loadData();
    
    $(document).ready(function () {
        ko.applyBindings(viewModel);
     });

</script>

<h2>Dodaj stanowisko</h2>
 <form id="myform">
     <p>@Html.Label("Nazwa stanowiska:")
         <input class='required' data-bind='value: Position.PositionName' />
     </p>
      <p>@Html.Label("Nabór:")
        <input type="checkbox" class='required' data-bind='checked: Position.Recruitment' />
    </p>
    @Html.Label("Kategorie pytań:")

     <ul data-bind="foreach: Categories">
        <li>        
            <input type="checkbox" data-bind="checked: selected, click: $parent.CategoriesModify" />
            <span data-bind="text: Name"></span>             
        </li>      
    </ul>         
    
     @Html.Label("Poziom trudności pytań:")
     <ul data-bind="foreach: Difficulties">
         <li>        
             <input type="checkbox" data-bind="checked: selected, click: $parent.QuestionDifficultiesToPositionModify" />
             <span data-bind="text: DifficultyName"></span>       
             <input style="width: 20px; margin-top: 3px; margin-bottom: 3px" data-bind="visible: selected, value: Quantity"/>   
         </li>      
     </ul>
     <!--event: { change: $parent.updatequestionAmount }, -->
      @Html.Label("Typ pytań:")
        <ul data-bind="foreach: QuestionTypes">
            <li>        
                <input type="checkbox" data-bind="checked: selected, click: $parent.QuestionTypesToPositionModify" />
                <span data-bind="text: Type"></span>
                <input style="width: 20px; margin-top: 3px; margin-bottom: 3px"  data-bind="visible: selected, value: Quantity"/>          
            </li>      
        </ul>
     
     @Html.Label("Łączna liczba pytań:")
     <span data-bind="text: questionAmount"></span>
     <span style="color: red" id="errorSpan"></span>
     <p>
        <button style="margin-top: 10px"data-bind="click: save">Dodaj stanowisko</button>
     </p>
    
 </form>
<style scoped="scoped">
  input.error { border: 1px solid red; background-color: #FDC; }
  label.error { display: block; color: Red; font-size: 0.8em; }
</style>